package com.example.volleysample;

import android.app.VoiceInteractor;
import android.util.Log;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;

import java.util.HashMap;
import java.util.Map;

import static com.android.volley.VolleyLog.TAG;

/**
 * Created by Administrator on 2017/8/30.
 */

public class HttpUtil {
    private IResponseListener mListener;

    public void setListener(IResponseListener Listener) {
        mListener = Listener;
    }

    public void doGet(final int action, String urlPath) {
        final String result;
        //传递一个URL对象----》String类型的JSON语句
        StringRequest request = new StringRequest(urlPath, new Response.Listener<String>() {
            //该方法是在主线程中执行的
            @Override
            public void onResponse(String response) {
                Log.i(TAG, "onResponse: " + response);
                if (mListener!=null){
                    mListener.onNetworkResponsed(action,response);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.i(TAG, "onErrorResponse: "+error.getLocalizedMessage());
            }
        });
        //一般 一个应用多个请求---》请求队列里面去
        MyApplication.getRequestQueue().add(request);
    }

    public void doPost(final int action, String urlPath, final HashMap<String,String> paramsMap){
        //传递一个URL对象----》String类型的JSON语句
        StringRequest request = new StringRequest(Request.Method.POST,urlPath, new Response.Listener<String>() {
            //该方法是在主线程中执行的
            @Override
            public void onResponse(String response) {
                Log.i(TAG, "POST onResponse: " + response);
                if (mListener!=null){
                    mListener.onNetworkResponsed(action,response);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                return paramsMap;
            }
        };
        MyApplication.getRequestQueue().add(request);
    }
}
